/**
 * @file: service.js
 * @description:
 * @author： YUWENJING
 * @date： 2020/2/15
 * @contact: wenjingyuer@126.com
 */

import Taro from '@tarojs/taro'
import {redirectWithAuth, toast} from "../../../utils";
import {getClassByClassKey} from "../../../service/index";
import {getGlobalData, setGlobalData} from "../../../global.d";
import {getUserById} from "../../../service";

const db = Taro.cloud.database();
const _ = db.command
/**
 * @description: 创建新班级
 * @param userId
 * @param userClass
 * @param classInfo
 * @author: YUWENJING
 * @date: 2020/2/15
 */
export async function createNewClass(userId, userClass,classInfo) {
  if(! await checkIfClassKeyExist(classInfo.classKey))
    return
  db.collection('class')
    .add({
      data: {
        createTime: new Date(),
        classKey:classInfo.classKey,
        classInfo,
        classStudents:[],
        classAdmins:[]
      }
    })
    .then(async res => {
      console.log(res);
      toast('保存成功');
     await updateUserLastTimeClassAndUserClass(userId,userClass,{
        className:classInfo.school+classInfo.majorOrClassName+classInfo.classNumber,
        type:'admin',
        classKey:classInfo.classKey
     })
      Taro.navigateBack();
    })
    .catch(err => {
      console.error(err);
    })
}


/**
 * @description: 检查密钥是否已经存在
 * @param {string} classKey - 班级密钥
 * @author: YUWENJING
 * @date: 2020/2/15
 */

 function checkIfClassKeyExist(classKey) {

  return  db.collection('class')
    .where({
      classKey
    })
    .get()
    .then(res => {
      if (res.data.length > 0) {
        toast('此密钥已存在，换一个叭')
        return false
      }
      return true
    })

}

/**
 * @description: 将新班级插入创建者班级并设为最近登陆班级
 * @author: YUWENJING
 * @date: 2020/2/15
 * @param userId
 * @param userClass
 * @param userLastTimeClass
 */


function updateUserLastTimeClassAndUserClass(userId,userClass,userLastTimeClass) {
  userClass.push(userLastTimeClass)
  db.collection('user')
    .doc(userId)
    .update({
      data: {
        userClass,
        userLastTimeClass
      }
    })
    .then( async res=>{
      console.log(res);
      const user = await getUserById(userId);
      setGlobalData('user', user);
      await addUserInClassAdmin(user,userLastTimeClass.classKey)
    })
}


/**
 * @description: 将创建者添加到班级管理者列表
 * @author: YUWENJING
 * @date: 2020/2/15
 * @param user
 * @param classKey
 */

async function addUserInClassAdmin(user,classKey) {

  let targetClass = await getClassByClassKey(classKey)
  let classId = targetClass._id
  db.collection('class')
    .doc(classId)
    .update({
      data:{
        classAdmins:_.push(user)
      }
    })
}
